/**
 * 
 */
package com.gomeplus.commons.quartz.factory;

import io.netty.channel.Channel;

import java.util.List;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

import com.gomeplus.commons.quartz.build.TaskBuildSource;
import com.gomeplus.commons.quartz.cache.QuartzConstants;
import com.gomeplus.commons.quartz.cache.QuartzPropertiesCache;
import com.gomeplus.commons.quartz.cache.QuartzTaskConfigCache;
import com.gomeplus.commons.quartz.netty.NettyMessage;
import com.gomeplus.commons.quartz.netty.client.NettyClientStartup;

/**
 * @author chenmin-ds
 * 任务链变更工厂
 */
public class ChildTimerUpdateFactory extends TimerTask {
	
	private Logger logger = LoggerFactory.getLogger("TimerTaskStartFactory");
	
	private TaskBuildSource taskBuildSourceProxy;
	
	private TaskInfoLoadInitsFactory taskInfoLoadInitsFactory;
	
	private long runCount = 0L;
	
	public ChildTimerUpdateFactory(TaskBuildSource taskBuildSourceProxy
			,TaskInfoLoadInitsFactory taskInfoLoadInitsFactory){
		this.taskBuildSourceProxy = taskBuildSourceProxy;
		this.taskInfoLoadInitsFactory = taskInfoLoadInitsFactory;
	}

	/* (non-Javadoc)
	 * @see java.util.TimerTask#run()
	 */
	@Override
	public void run() {
		if(QuartzConstants.TASK_INFO_LOAD_TYPE_REMOTE.equals(QuartzPropertiesCache.getTaskInfoLoadType())){
			remote();
		}else{
			dao();
		}
	}

	private void dao(){
		try{
			runCount ++;
			logger.info("任务链变更工厂执行任务变更开始，当前是第[{}]次",runCount);
			List<JSONObject> list = taskInfoLoadInitsFactory.loadTaskInfoDao();
			JSONObject oldValue = null;
			for(JSONObject object : list){
				oldValue = QuartzTaskConfigCache.getTaskInfo(object.getString("taskNo"));
				if(null != oldValue && !QuartzTaskConfigCache.checkUpdate(object)){
					list.remove(object);
					continue;
				}
				taskBuildSourceProxy.updateTask(object);
				QuartzTaskConfigCache.setTaskInfo(object.getString("taskNo"), object);
			}
		}catch(Exception e){
			logger.error("任务链变更工厂执行任务变更异常",e);
		}
	}
	
	private void remote(){
		try{
			runCount ++;
			logger.info("任务链变更工厂执行任务变更开始，当前是第[{}]次",runCount);
			Channel channel = NettyClientStartup.getInstance().getChannel();
			NettyMessage nettyMessage = new NettyMessage(QuartzConstants.BUSINESS_TYPE_RWXXCX_UPDATE);
			nettyMessage.setJsonObject("BUSINESS_CODE", QuartzPropertiesCache.getBusinessCode());
			channel.writeAndFlush(nettyMessage);
		}catch(Exception e){
			logger.error("任务链变更工厂执行任务变更异常",e);
		}
	}
}
